const fs = require('fs')
const path = require('path')


function preParellDeep(dir, callback) {
    console.log('dir1=>', dir, callback)
    fs.stat(dir, function (err, stat) {
        if (stat.isFile()) {
            console.log('object=>', dir, callback)
            fs.unlink(dir, callback)
        } else {
            fs.readdir(dir, function (err, dirs) {
                dirs = dirs.map(item => path.join(dir, item))
                console.log('dirs=>', dirs, dir)
                if (dirs.length === 0) return fs.rmdir(dir, callback)
                let index = 0;
                function done() {
                    console.log('dirr =>', dir)
                    if (++index === dirs.length) return fs.rmdir(dir, callback)
                }
                dirs.forEach(dir => {
                    console.log('dir2=>', dir, done)
                    preParellDeep(dir, done)
                })
            })
        }
    })
}

preParellDeep(path.resolve(__dirname, 'a'), () => {
    console.log('删除成功')
})

